<?php
/**
 * Created by PhpStorm.
 * User: suncco
 * Date: 2018/8/6
 * Time: 16:11
 */

namespace app\admin\logic;

use think\Model;
use tree\Tree;


class CategoryLogic extends Model{

    /**
     * 获取栏目列表
     * @param string $where
     * @return mixed
     */
    public function getCatListAttr($where=""){
        $category = db('category')
                    ->field('id,pid,name')
                    ->order('o asc')
                    ->where($where)
                    ->select();

        return $category;
    }
    /**
     * 文章分类逻辑定义
     * Class CategoryLogic
     * @package app\admin\logic
     *
     * 无法实现无限极分类，此处还需修改
     */
    public function getCatList($items, $id = 'id', $pid = 'pid', $son = 'children'){
        $tree = array();
        $tmpMap = array();
        foreach( $items as $item ){
            if( $item['pid']==0 ){
                $father_ids[] = $item['id'];
            }
        }
        //----
        foreach ($items as $item) {
            $tmpMap[$item[$id]] = $item;
        }

        foreach ($items as $item) {
            if( $item['pid']<>0 && !in_array( $item['pid'], $father_ids )){
                continue;
            }
            //----
            if (isset($tmpMap[$item[$pid]])) {
                $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
            } else {
                $tree[] = &$tmpMap[$item[$id]];
            }
        }
        return $tree;
    }

    /**
     * 通过tree插件进行树形排序
     * @param $pid
     * @param $category
     * @return string
     */
    public function getCatTree($pid,$category){
        $tree = new Tree($category);
        $str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
        $category = $tree->get_tree(0, $str, $pid);

        return $category;
    }

    //设置栏目排序
    public function setOrder($id,$o){
        db('category')->data(array('o' => $o))->where("id='{$id}'")->update();
        addlog('分类修改排序，ID：' . $id);
    }

}